<?php
/**
 * Note: 验证码消息
 */
namespace App\Messages;

use App\Caches\SmsSignCache;
use iBrand\Sms\Code;
use Overtrue\EasySms\Contracts\GatewayInterface;
use Overtrue\EasySms\Message;
use Overtrue\EasySms\Strategies\OrderStrategy;

class CaptchaMessage extends Message
{
    /**
     * @var Code
     */
    protected $code;

    /**
     * @var int
     */
    protected $minutes;

    /**
     * @var string
     */
    protected $signName;

    protected $strategy = OrderStrategy::class;

    protected $gateways = ['chuanglan'];

    public function __construct(Code $code, int $minutes, int $sourceId = null)
    {
        $this->code = $code;
        $this->minutes = $minutes;
        $this->signName = $this->getSignName($sourceId);

        // 调试模式时使用 日志
        if (config('app.debug')) $this->gateways = ['errorlog'];
    }

    /**
     * 短信内容
     * @param GatewayInterface|null $gateway
     * @return string
     */
    public function getContent(GatewayInterface $gateway = null): string
    {
        $content = sprintf("您的验证码是%s，%d分钟内有效，如非本人操作，请忽略本短信。", $this->code->code, $this->minutes);
        // 创蓝非默认签名, 需要指定
        if ($gateway->getName() === 'chuanglan' && $this->signName) {
            $content = "【{$this->signName}】{$content}";
        }
        return $content;
    }

    protected function getSignName(int $sourceId = null)
    {
        $default = config('ibrand.sms.sign_name');
        if (!$sourceId) {
           return $default;
        }
        return SmsSignCache::getBySourceId($sourceId) ?? $default;
    }
}
